# -*- coding: utf-8 -*-
# @Date    : 2022-11-14 09:10
# @Author  : chenxuepeng
import time
import os
import json
from selenium import webdriver
from .useragent import get_ua
from .mongoApi import MongoConn
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager

MonConn = MongoConn(log=False, db='apitools')


class RpcSpider(object):

    def __init__(self, url: str = None, task_id: str = None):
        data_dict = {}
        start_cookie_dict = {}
        option = webdriver.FirefoxOptions()
        option.add_argument('--headless')
        option.add_argument('--user-agent={}'.format(get_ua))
        self.driver = webdriver.Firefox(service=FirefoxService(
            GeckoDriverManager().install()), options=option)
        check_url = url
        self.driver.get(check_url)
        self.driver.implicitly_wait(10)
        cookie = self.driver.get_cookies()
        for c in cookie:
            key, value = c.get('name', None), c.get('value', None)
            start_cookie_dict[key] = value
        pid = self.get_os_id()
        data_dict['url'] = url
        data_dict['task_id'] = task_id
        data_dict['pid'] = pid
        data_dict['status'] = 'run'
        data_dict['start_cookie'] = start_cookie_dict
        while True:
            code = self.open_selenium()
            data_dict['cookie'] = code
            MonConn.updated_one('RpcSpider', {'task_id': task_id}, data_dict)

    def open_selenium(self):
        # self.driver.refresh()
        ck = {}
        rpc_code = 'return document.cookie'
        code = self.driver.execute_script(rpc_code)
        code = code.split(';') if code else code
        if code:
            for i in code:
                if i.find('=') != -1:
                    key, value = i.split('=')
                    ck[key.strip()] = value
        return ck

    def close_selnium(self):
        self.driver.close()
        self.driver.quit()

    def get_os_id(self):
        return os.getpid()

    def __del__(self):
        self.driver.close()
        self.driver.quit()


if __name__ == '__main__':
    r = RpcSpider(
        url='https://etax.qingdao.chinatax.gov.cn:7553/sso/login', task_id="qingdao")
